package cc.jinglupeng.wechat;

import java.util.HashMap;
import java.util.Map;

import cc.jinglupeng.wechat.bean.AccessToken;
import cc.jinglupeng.wechat.bean.JSAPITicket;

public class DefaultWechatCache implements WechatCache {
	private static final Map<String, JSAPITicket> JSAPITICKET_CACHE = new HashMap<String, JSAPITicket>();
	private static final Map<String, AccessToken> ACCESSTOKEN_CACHE = new HashMap<String, AccessToken>();
	public static int ACCESSTOKEN_CACHE_TIME = 6000;
	public static int JSAPITICKET_CACHE_TIME = 6000;

	@Override
	public AccessToken getAccessToken(String appId) {
		AccessToken token = ACCESSTOKEN_CACHE.get(appId);
		if (token == null)
			return null;
		Long now = System.currentTimeMillis();
		Long old = token.getCreateTime();
		if (now - old > ACCESSTOKEN_CACHE_TIME * 1000) {
			return null;
		}
		return token;
	}

	@Override
	public void cacheAccessToken(String appId, AccessToken accessToken) {
		ACCESSTOKEN_CACHE.put(appId, accessToken);
	}

	@Override
	public JSAPITicket getJSAPITicket(String appId) {
		JSAPITicket ticket = JSAPITICKET_CACHE.get(appId);
		if (ticket == null)
			return null;
		Long now = System.currentTimeMillis();
		Long old = ticket.getCreateTime();
		if (now - old > JSAPITICKET_CACHE_TIME * 1000) {
			return null;
		}
		return ticket;
	}

	@Override
	public void cacheJSAPITicket(String appId, JSAPITicket ticket) {
		JSAPITICKET_CACHE.put(appId, ticket);
	}

}
